<?php

class studentController extends BaseController
{

    public function __init()
    {
        //此控制器初始化时，执行代码
        SS('setup', M('setups')->get(getroom()));
        if (!GS('setup')) {
            flashMsg('/index/login', "上课班级未设置！");
        }
        $class_id = GS('setup')['class_id'];
        SS('student', M('students')->getOne($class_id, getSite()));
        if (!GS('student')) {
            flashMsg('/index/register', "无名学生，请先注册！");
        }
    }

// 新首页 根据数据库记录判断有无上传
    public function index()
    {
        $stuID  = GS('student')['id'];
        $taskID = GS('setup')['task_id'];
        $r      = db('upRecords')->where('stuID=? AND taskID=?', [$stuID, $taskID])->order('updated DESC')->fetch();
        if ($r) {
            $this->filesize = betterSize(filesize(PG_UP . $r['filePath']));
        }

        $this->title = '首 页';
    }

//下载课程
    public function downTask()
    {
        $ID   = I('taskID');
        $task = M('tasks')->getByID($ID);
        $name = $task['name'];
        $ext  = $task['ext'];
        $user = GS('setup')['teacher_username'];
        if (!$user) {$user = GS('auth')['name'];}
        $url      = '教师' . $user . '/课程/' . $ID . '.' . $ext;
        $saveName = $name . '.' . $ext;
        hideDownload($url, $saveName);
    }

//学生下载自己的作业
    public function downZY()
    {
        $site    = getSite();
        $stuName = GS('student')['name'];
        $taskID  = I('taskID');
        $stuID   = GS('student')['id'];
        $r       = db('upRecords')->where('stuID=? AND taskID=?', [$stuID, $taskID])->order('updated DESC')->fetch();
        if ($r) {
            $path     = explode('/', $r['filePath']);
            $saveName = end($path);
            hideDownload($r['filePath'], $saveName);
        }
        flashMsg('/student/task', "你的作业不存在，下载失败！", '错误', 2);
    }

//ajax上传作业
    public function upZY()
    {

        $task = I('task');
        $user = GS('setup')['teacher_username'];
        if (empty($user)) {
            $r['code'] = 1;
            $r['msg']  = '登录超时,请重新上传.';
            json($r);
        }
        $bj       = GS('setup')['class_name'];
        $site     = GS('student')['site'];
        $stuName  = GS('student')['name'];
        $ext      = extName($_FILES['file']['name']);
        $saveName = $site . $stuName . '.' . $ext;
        $path     = '教师' . $user . '/作业/' . $bj . '班/课程' . $task . '/';
        if (!empty($_FILES['file'])) {
            $uper = new phpGrace\tools\uper('file', PG_UP . $path, $saveName);
            $uper->allowAllFile = 'yes'; //允许上传所有文件
            // $uper->allowType = 'application/x-zip-compressed
            // ,application/x-rar-compressed
            // ,application/zip
            // ,application/octet-stream
            // ,text/plain
            // ,application/msword
            // ,application/vnd.openxmlformats-officedocument.wordprocessingml.document
            // ,application/vnd.ms-excel
            // ,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
            // ,text/x-python';
            // $uper->allowExeName = 'zip,rar,7z,txt,doc,docx,xls,xlsx,py'; //允许上传文件的扩展名

            $uper->allowSize = 20 * 1024; //允许上传文件的大小 [单位 KB]
            $zy              = $uper->upload();
            if ($zy) {
                $data['stuID']    = GS('student')['id'];
                $data['taskID']   = $task;
                $data['filePath'] = $path . $saveName;
                $data['updated']  = date('Y-m-d H:i:s');
                $r                = db('upRecords')->where('stuID=? AND taskID=?', [$data['stuID'], $task])->fetch();
                if ($r) {
                    //更新
                    db('upRecords')->where('id=?', $r['id'])->update($data);
                } else {
                    //新增
                    db('upRecords')->add($data);
                }
                $r['code'] = 0;
                $r['msg']  = '上传成功';

            } else {
                $r['code'] = 1;
                $r['msg']  = $uper->error;
            }
            json($r);
        }

    }

// 游戏中心
    public function Game()
    {
        if (IS_POST()) {
            // 获取游戏记录填入前台表格
            $r = M('games')->getByUserID(GS('setup')['teacher_id']);
            json($r);
        }
        // 游戏中心关闭时禁止访问本页
        if (GS('setup')['allow_game'] == '0') {
            flashMsg('/student/index', "时辰未到，少年请回！");
        }

        $this->title = '游戏中心';

    }

//下载游戏
    public function downGame()
    {

        $setup = GS('setup');
        //游戏中心未开,禁止下载
        if ($setup['allow_game'] == '0') {
            flashMsg('/', "时辰未到，少年请回！");
        }
        $student = GS('student');
        $kf      = true; //是否扣分
        //游戏中心已打开时
        $game = db('games')->where('id=?', I('id'))->fetch();
        //判断是否下载过该游戏
        $lastDown = db('points')->where('stu_id=? and reason=?', [$student['id'], '下载游戏：' . $game['name']])->order('id DESC')->fetch();
        $price    = $game['price'];
        if (!empty($lastDown)) {
            //之前下载过该游戏,若已过时间大于120分钟，则同样扣分
            $lastDownTime = strtotime($lastDown['created']);
            $timepass     = (time() - $lastDownTime) / 60;
            $kf           = ($timepass > 120) ? true : false;
        }
        if ($kf == true) {
            if ($student['game_point'] < $price) {
                flashMsg('/student/game', '积分不足，下载失败！');
            }
            $v['stu_id']  = $student['id'];
            $v['task_id'] = $setup['task_id'];
            $v['point']   = -$price;
            $v['reason']  = '下载游戏：' . $game['name'];
            $v['type']    = '游戏扣分';
            // 新增扣除游戏积分记录,并更新学生信息
            db('points')->add($v);
            db('students')->where('id=?', $student['id'])->field('game_point', -$price);
        }
        $url = '教师' . GS('setup')['teacher_username'] . '/游戏/' . $game['file'];
        db('games')->where('id=?', I('id'))->field('hits', 1);
        //符合条件、开始下载游戏
        //header('location:/' . $url); // 1、直接下载会暴露真实地址
        hideDownload($url, $game['name']); // 2、隐藏地址下载，使用下载软件时点击数会自动加N
    }

    public function Task()
    {
        if (IS_POST()) {
            $cat                          = I('cat');
            $json['data']                 = M('tasks')->getByCatID($cat);
            $json['data'] ? $json['code'] = 0 : $json['msg'] = '本分类下暂无课程';
            json($json);
        }
        $this->cats  = M('categorys')->getByUserID(GS('setup')['teacher_id']);
        $this->title = '所有课程';

    }

// 查看积分记录
    public function Record()
    {
        //取积分记录
        if (PG_POST) {
            $who    = I('who');
            $stu_id = null;
            if ($who == '0') {
                $stu_id = I('stu_id');
                $bj     = GS('setup')['class_id'];
            } else {
                $bj = $who;
            }

            $type  = I('type');
            $limit = I('limit');
            $begin = (I('page') - 1) * $limit; //分页
            return M('Points')->get($bj, $type, $stu_id, $begin, $limit);
        } else {
            $this->classes = M('classes')->getClassByTeacher(GS('setup')['teacher_id']);
            $this->title   = '积分记录';
        }
    }

//page: 难题统计
    public function hardCount()
    {
        // 学生提交答案
        if (PG_POST) {
            $begin = I('begin');
            // 去除答案中的空格
            $answers = str_replace(" ", "", I('answers'));
            // 计算输入的答案个数
            $total     = strlen($answers);
            $错误数 = 0;
            if ($total != I('total')) {
                die('答案数目不对，请检查输入');
            } else {
                $v['class_id'] = gs('setup')['class_id'];
                $v['stu_id']   = gs('student')['id'];
                $v['count_id'] = I('count_id');
                $v['answers']  = $answers;

                $rightAnswer = db('hardCount')->where('id=?', [I('count_id')])->fetch('answers');
                $rightAnswer = str_split($rightAnswer['answers']);
                $answers     = str_split(strtoupper($answers));
                $wrong       = '';
                foreach ($answers as $key => $answer) {
                    if ($answer != $rightAnswer[$key]) {
                        $wrong .= '第' . ($key + $begin) . '题_正确答案为：' . $rightAnswer[$key] . '<br>';
                        $错误数++;
                    }
                }
                if ($wrong == '') {
                    $wrong = '<h3>太厉害了,没有错题!</h3>';
                }

                $得分      = round((100 / $total) * ($total - $错误数));
                $v['得分'] = $得分;
                $返回      = $wrong . '<br><h2 style="color:blue"> 得分: ' . $得分 . '分</h2>';

                // 查询是否已经提交过统计
                $r = db('hardCountStu')->where('stu_id=? AND count_id=?', [$v['stu_id'], $v['count_id']])->fetch();
                // 未提交过,新增记录
                if (!$r) {
                    db('hardCountStu')->add($v);
                    die('<h3 style="color:red">首次提交</h3><br>' . $返回);
                } else {
                    die('<h3 style="color:red">非首次提交</h3><br>' . $返回);
                }
            }
        } else {
            // 显示提交答案界面
            $this->title = '难题调查';
            $w1          = 'teacher_id=? AND switch=1';
            $w2          = gs('setup')['teacher_id'];
            $r           = db('hardCount')->where($w1, $w2)->order('id DESC')->fetch();
            if ($r) {
                $this->count = $r;
            } else {
                flashMsg('/', "暂无难题调查");
            }
        }
    }

//打字高手
    public function master()
    {
        $teacher_uid=gs('setup')['teacher_username'];
        $filepath=PG_UP .'教师'.$teacher_uid. '/打字高手截图/_打字高手.xlsx';
        if (!file_exists($filepath)){
            flashMsg('/student/index',"高手排行文件不存在，请等待老师上传！","错误");
        }
        //实例化 excel 读取对象
        $PHPExcelReader = tool('PHPExcelReader');

        //读取指定的 excel 文件
        $sheets      = $PHPExcelReader->read($filepath);
        unset($sheets[0]['data'][0]);
        // 提取要排序的列
        $mc = array_column($sheets[0]['data'], 6);
        // 根据提取的列进行排序
        array_multisort($mc, SORT_ASC, $sheets[0]['data']);
        $this->data  = $sheets[0]['data'];
        //pd($this->data);
        $this->title = '打字高手榜';
    }
    //上传打字精灵成绩截图
    public function upPic()
    {

        $user = GS('setup')['teacher_username'];
        if (empty($user)) {
            $r['code'] = 1;
            $r['msg']  = '登录超时,请重新上传.';
            json($r);
        }
        $bj       = GS('setup')['class_name'];
        $site     = GS('student')['site'];
        $stuName  = GS('student')['name'];
        $oldFilename = $_FILES['file']['name'];
        $ext      = extName($oldFilename);
        $saveName = $bj.'班_'.$site."_" . $stuName ."_". $oldFilename . '.' . $ext;
        $path     = '教师' . $user . '/打字高手截图/';
        if (!empty($_FILES['file'])) {
            $uper = new phpGrace\tools\uper('file', PG_UP . $path, $saveName);
            $uper->allowAllFile = 'yes'; //允许上传所有文件
            $uper->allowSize = 20 * 1024; //允许上传文件的大小 [单位 KB]
            $zy              = $uper->upload();
            if ($zy) {
                $r['code'] = 0;
                $r['msg']  = '上传成功';

            } else {
                $r['code'] = 1;
                $r['msg']  = $uper->error;
            }
            json($r);
        }

    }

} //end
